//
//  LRXMenuVIew.m
//  路人侠
//
//  Created by zhangxulong on 3/9/16.
//  Copyright © 2016 zhangxulong. All rights reserved.
//

#import "LRXMenuView.h"
#import "TWTSideMenuViewController.h"
#import "LRXLoginViewController.h"
#import "zxlCircleView.h"
#import "LRXUserModel.h"
#import "LRXUserInfoView.h"
#import "LRXMyHelpItemController.h"
#import "LRXSettingController.h"
#import "LRXHistroyHelpItemController.h"
#import "UIButton+WebCache.h"
#import "AppDelegate.h"
#import "LRXPocketMoneyController.h"
#import "LRXDistributionController.h"
static NSString * updateUserInfoUrl = @"http://120.24.7.51/app/Auth/updateUserInfo";
//单例模式
static LRXMenuView * _instance = nil;
static NSString * imagePath;
static NSString *imageDocPath;
@interface LRXMenuView()<
    UIImagePickerControllerDelegate,
    UINavigationControllerDelegate
>

@property (nonatomic, strong) UIImageView *backgroundImageView;
@property (nonatomic,weak) UIButton * userIcon;
@property (nonatomic,copy) NSString * imageRoute;
@property (nonatomic,strong) UIProgressView * progressView;
@property (nonatomic,copy) NSString * userName;
@property (nonatomic,weak) UIButton * userNameBtn;
@property (nonatomic,weak) UIView  * backgroundView;

@property (nonatomic,weak) AppDelegate * appDelegate;

@end

@implementation LRXMenuView
- (UIProgressView *)progressView
{
    if (_progressView == nil) {
        _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
        
    }
    return _progressView;
}

//单例模式
+(instancetype) shareInstance
{
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init] ;
    }) ;
    
    return _instance ;
}
+ (void)initialize
{
    //获取Documents文件夹目录
    NSString *documentPath  = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    //指定新建文件夹路径
    imageDocPath = [documentPath stringByAppendingPathComponent:@"ImageFile"];
    //创建ImageFile文件夹
    [[NSFileManager defaultManager] createDirectoryAtPath:imageDocPath withIntermediateDirectories:YES attributes:nil error:nil];
    
    
}

- (void)viewDidLoad
{
   
    [super viewDidLoad];
  
    self.view.backgroundColor = [UIColor blackColor];
    self.backgroundImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"sideback2"]];
  
    self.backgroundImageView.translatesAutoresizingMaskIntoConstraints = YES;
    CGRect imageViewRect = [[UIScreen mainScreen] bounds];
    imageViewRect.size.width *= 2;
    imageViewRect.origin.x -= imageViewRect.size.width * 0.25;
    self.backgroundImageView.frame = imageViewRect;
    self.backgroundImageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:self.backgroundImageView];
    
    CGFloat myBringButtonY = 376 * hScale;
    CGFloat buttonH = 111 * hScale;
    CGFloat buttonW = 460 * wScale;
    CGFloat buttonInH = 32 * hScale;
    
    //用户的信息
    LRXUserModel * userModel = [NSKeyedUnarchiver unarchiveObjectWithFile:userFilePath];
    UIButton * myBringButton = [UIButton buttonWithType:UIButtonTypeSystem];
    myBringButton.titleLabel.font = [UIFont systemFontOfSize:34 * hScale];
    myBringButton.frame = CGRectMake(0 , myBringButtonY, buttonW, buttonH);
    [myBringButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [myBringButton setTitle:@"我的帮带" forState:UIControlStateNormal];
    [myBringButton addTarget:self action:@selector(pushMyBringView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:myBringButton];
    

    UIButton *myHelpBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    myHelpBtn.frame = CGRectMake(0, CGRectGetMaxY(myBringButton.frame) + buttonInH, buttonW, buttonH);
    myHelpBtn.titleLabel.font = [UIFont systemFontOfSize:34 * hScale];
    [myHelpBtn setTitle:@"我的求带" forState:UIControlStateNormal];
    [myHelpBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [myHelpBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [myHelpBtn addTarget:self action:@selector(pushMyHelpView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:myHelpBtn];
    
    
    
    UIButton * pocketBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    pocketBtn.frame = CGRectMake(0, CGRectGetMaxY(myHelpBtn.frame) + buttonInH,buttonW, buttonH);
    pocketBtn.titleLabel.font = [UIFont systemFontOfSize:34 * hScale];
    [pocketBtn setTitle:@"我的逗币" forState:UIControlStateNormal];
    [pocketBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [pocketBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [pocketBtn addTarget:self action:@selector(pushPocket) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pocketBtn];
    
    UIButton * setBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    setBtn.frame = CGRectMake(0, CGRectGetMaxY(pocketBtn.frame) + buttonInH, buttonW, buttonH);
    setBtn.titleLabel.font = [UIFont systemFontOfSize:34 * hScale];
    [setBtn setTitle:@"设置" forState:UIControlStateNormal];
    [setBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [setBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [setBtn addTarget:self action:@selector(pushSetView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:setBtn];
    

    
    UIButton * userIcon = [UIButton buttonWithType:UIButtonTypeCustom];
    userIcon.frame = CGRectMake(60 * wScale, 93 * hScale, 160 * hScale, 160 * hScale);
    userIcon.layer.cornerRadius = userIcon.frame.size.width * 0.5;
    userIcon.layer.borderColor = [UIColor whiteColor].CGColor;
    userIcon.layer.borderWidth = 2 * hScale;
    userIcon.layer.masksToBounds = YES;
    self.userIcon = userIcon;
    
    self.userName = userModel.userName.length > 0 ? userModel.userName:@"路人侠";
    UIButton * userName = [UIButton buttonWithType:UIButtonTypeSystem];
    userName.bounds = CGRectMake(0, 0, 400 * wScale, 31 * hScale);
    [userName setTitle:self.userName forState:UIControlStateNormal];
    [userName setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    userName.titleLabel.textAlignment = NSTextAlignmentCenter;
    userName.titleLabel.font = [UIFont systemFontOfSize:31 * hScale];
    
    userName.center = CGPointMake(userIcon.center.x, CGRectGetMaxY(userIcon.frame) + 35 * hScale );
    [userName addTarget:self action:@selector(fixUserName) forControlEvents:UIControlEventTouchUpInside];
    self.userNameBtn = userName;
    [self.view addSubview:userName];
    
    NSString * sexy;
    if ([userModel.sexy isEqualToString:@"1"])
        sexy = @"俏小姐";
    else if([userModel.sexy isEqualToString:@"0"])
        sexy = @"帅小伙";
    else
        sexy = @"外星人";
    
    UILabel * sexLabel = [[UILabel alloc]init];
    sexLabel.text = sexy;
    sexLabel.font = [UIFont systemFontOfSize:20 *  hScale];
    [sexLabel sizeToFit];
    sexLabel.center = CGPointMake(userIcon.center.x, CGRectGetMaxY(userName.frame) + 30 *hScale);
    sexLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:sexLabel];
    
    CGFloat serViewX = CGRectGetMaxX(userIcon.frame) + 53 * wScale;
    CGFloat serViewY = 100 * hScale;
    CGFloat userInfoH = 28 * hScale;
    CGFloat userInfoW = 200 * wScale;
    CGFloat userInfoInH = 40 * hScale;
    
    
    LRXUserInfoView * serView = [[LRXUserInfoView alloc]init];
    serView.frame = CGRectMake(serViewX, serViewY, userInfoW, userInfoH);
    [serView layoutSubviews:@"速度" numberWith:userModel.speed_rank];
    [self.view addSubview:serView];
    
    LRXUserInfoView * speeView = [[LRXUserInfoView alloc]init];
    speeView.frame = CGRectMake(serViewX, CGRectGetMaxY(serView.frame) + userInfoInH, userInfoW, userInfoH);
    [speeView layoutSubviews:@"服务" numberWith:userModel.manner_rank];
    [self.view addSubview:speeView];
    
    
    LRXUserInfoView * belView = [[LRXUserInfoView alloc]init];
    belView.frame = CGRectMake(serViewX, CGRectGetMaxY(speeView.frame) + userInfoInH, userInfoW, userInfoH);
    [belView layoutSubviews:@"信誉" numberWith:userModel.is_verify];
    [self.view addSubview:belView];
    
    

    
    self.appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    

    
    NSString * userImageStr = @"";
    if ([userModel.userImage isEqual:[NSNull null]] || !userModel.userImage  || !userModel ) {
        userImageStr = @"";
    }
    else
        userImageStr = userModel.userImage;
    
    NSString * userImage = [routeImageUrl stringByAppendingString:userImageStr];

    NSLog(@"头像 url  %@  本地头像 %@ ",userImage ,userModel.userImage);
    
    
    [userIcon sd_setImageWithURL:[NSURL URLWithString:userImage] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"de"] options:SDWebImageRefreshCached];
    
    
    
    [self.view addSubview:userIcon];
    
    [userIcon addTarget:self action:@selector(pushLogAndRegView) forControlEvents:UIControlEventTouchUpInside];
}

//打开注册和登录
- (void)pushLogAndRegView
{
    NSArray * cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    
    //判断NSHTTPCookie cookies 中的name的值有 “r_随即串”
    BOOL cookiesFlag = NO;
    for (NSHTTPCookie * cookie in cookies) {
        if ([cookie.name hasPrefix:@"r_"]) {
            cookiesFlag = YES;
            break;
        }
    }
    if(cookiesFlag) {
        [self localPhoto];
    }
    else
    {
        [self.sideMenuViewController changMainViewController:[LRXLoginViewController new] animated:YES closeMenu:YES];
    }
}

//打开相册
- (void)localPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    UIAlertController * alerView = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    //资源类型为图片库
    UIAlertAction * photoLibray = [UIAlertAction actionWithTitle:@"相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:picker animated:YES completion:nil];
        
    }];
    
    //资源类型为相机
    UIAlertAction * Camera = [UIAlertAction actionWithTitle:@"相机拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
         [self presentViewController:picker animated:YES completion:nil];
      
    }];

    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alerView addAction:photoLibray];
    [alerView addAction:Camera];
    [alerView addAction:cancel];
    [self presentViewController:alerView animated:YES completion:nil];
   

    
}

#pragma mark Delegate method UIImagePickerControllerDelegate
//图像选取器的委托方法，选完图片后回调该方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    
    self.progressView.bounds = CGRectMake(0, 0, 400 * wScale, 5 * hScale);
    self.progressView.center = CGPointMake(MainScreenW * 0.5, MainScreenH * 0.5);
    UIView * backgroundView = [[UIView alloc]init];
    backgroundView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.54];
    backgroundView.frame = CGRectMake(0, 0, 640 * wScale, MainScreenH);
    
    
    [[UIApplication sharedApplication].keyWindow addSubview:backgroundView];
    [[UIApplication sharedApplication].keyWindow addSubview:self.progressView];
    

    //当图片不为空时显示图片并保存图片
    if (image != nil) {
        //使用照片 保存路径 已经获取到了路径了
        [self adduserIconPic:image];
        

        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:updateUserInfoUrl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            
            [formData appendPartWithFileURL:[NSURL fileURLWithPath:self.imageRoute] name:@"profile" error:nil];
            
        } error:nil];
        AFURLSessionManager * manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

        NSURLSessionUploadTask *uploadTask;
        uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
                          dispatch_async(dispatch_get_main_queue(), ^{
                              [self.progressView setProgress:uploadProgress.fractionCompleted];
                          });
                      }
                      completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                          [self.progressView removeFromSuperview];
                          [backgroundView removeFromSuperview];
                          
                          if(error)
                          {
                              NSLog(@"%@",error);
                              [MBProgressHUD showError:@"网络连接错误"];
                          }
                      }];
        
        [uploadTask resume];
        
    }
    //关闭相册界面
    [picker dismissViewControllerAnimated:YES completion:nil];
}
//设置缓存和设置头像照片
- (void)adduserIconPic:(UIImage * )image
{
    //图片显示在界面上
    [self.userIcon setImage:image forState:UIControlStateNormal];


    //压缩图片
    NSData * data = UIImageJPEGRepresentation(image, 0.5f);
    //获取账号，根据账号添加图片路径
    NSString * str = [[NSUserDefaults standardUserDefaults] objectForKey:@"ident"];
    str = [str stringByAppendingString:@"userIcon.png"];
    
    //账户保存图片的路径 这个方法可以自动添加 \ 路径分割符
    imagePath = [imageDocPath stringByAppendingPathComponent:str];
    self.imageRoute = imagePath;
    //保存到磁盘文件
    [[NSFileManager defaultManager] createFileAtPath:imagePath contents:data attributes:nil];
}

- (void)pushMyBringView
{
    
    if(self.appDelegate.userRole == USERHELPERTYPR)
    {
        [self.sideMenuViewController changMainViewController:[LRXDistributionController new] animated:YES closeMenu:YES];
    }
    else if(self.appDelegate.userRole == USEROFFLINETYPE)
    {
         [self.sideMenuViewController changMainViewController:[LRXLoginViewController new] animated:YES closeMenu:YES];
    }
    else if(self.appDelegate.userRole == USERNORMALTYPE)
    {
        [self.sideMenuViewController changMainViewController:[LRXHistroyHelpItemController new] animated:YES closeMenu:YES];
    }
}

- (void)pushMyHelpView
{
    if(self.appDelegate.userRole == USEROFFLINETYPE)
    {
        [self.sideMenuViewController changMainViewController:[LRXLoginViewController new] animated:YES closeMenu:YES];
    }
    else
    {
        [self.sideMenuViewController changMainViewController:[LRXMyHelpItemController new] animated:YES closeMenu:YES];
    }
}
- (void)pushSetView
{
    if(self.appDelegate.userRole == USEROFFLINETYPE)
    {
         [self.sideMenuViewController changMainViewController:[LRXLoginViewController new] animated:YES closeMenu:YES];
    }
    else{
        [self.sideMenuViewController changMainViewController:[LRXSettingController new] animated:YES closeMenu:YES];
    }
    
}
- (void)pushPocket
{
    if(self.appDelegate.userRole == USEROFFLINETYPE)
    {
         [self.sideMenuViewController changMainViewController:[LRXLoginViewController new] animated:YES closeMenu:YES];
    }
    else
    {
        [self.sideMenuViewController changMainViewController:[LRXPocketMoneyController new] animated:YES closeMenu:YES];
    }
    
}

//修改姓名
- (void)fixUserName
{
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"修改用户名" message:@"确认修改吗？" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
        textField.placeholder = self.userName;
        textField.font = [UIFont systemFontOfSize:25 * hScale];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *userName = alertController.textFields.firstObject;
        [self updateUserName:userName.text];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];    
}


- (void)updateUserName:(NSString *)userName
{
    //去除蒙板
    [self.backgroundView removeFromSuperview];
    [self.userNameBtn setTitle:userName forState:UIControlStateNormal];
    self.userName = userName;
    
    LRXUserModel * userModel = [NSKeyedUnarchiver unarchiveObjectWithFile:userFilePath];
    userModel.userName = userName;
    [NSKeyedArchiver archiveRootObject:userModel toFile:userFilePath];
    [self.userNameBtn.titleLabel sizeToFit];
    
    [MBProgressHUD showMessage:@"正在提交"];
    AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
    NSDictionary * dic = @{@"name":userName};
    [manger POST:updateUserInfoUrl parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         [MBProgressHUD hideHUD];
        if ([responseObject[@"data"][@"status_code"] isEqualToString:@"1"]) {
            [MBProgressHUD showSuccess:@"提交成功"];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络连接错误"];
    }];
}
//当打开导航栏的时候 状态栏变成白色
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
- (void)cancelButtonPressed{
    [self viewDidLoad];
    [self.sideMenuViewController changMainViewController:[LRXLoginViewController new] animated:YES closeMenu:YES];
    
}

@end
